package org.example.project.micro.util;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import lombok.extern.slf4j.Slf4j;
import org.example.project.common.util.SpringBeanHolder;
import org.example.project.common.contant.Log;
import org.example.project.micro.event.ConfigurationChangeEvent;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;

import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
 * @author wenxy
 * @date 2020/11/9
 */
@Slf4j
public class ConfigurationRefreshUtils {

    public static void refresh(ConfigChangeEvent configChangeEvent) {
        SpringBeanHolder.publishEvent(new EnvironmentChangeEvent(configChangeEvent.changedKeys()));
        logRefresh(configChangeEvent);
    }

    public static void refreshCustom(ConfigChangeEvent configChangeEvent) {
        SpringBeanHolder.publishEvent(new ConfigurationChangeEvent(configChangeEvent.changedKeys()));
        logRefresh(configChangeEvent);
    }

    public static void logRefresh(ConfigChangeEvent configChangeEvent) {
        if (log.isInfoEnabled()) {
            log.info(Log.builder()
                    .param(configChangeEvent.changedKeys()
                            .stream().map(key -> configChangeEvent.getChange(key))
                            .collect(Collectors.toList()))
                    .result("refresh configuration properties ok")
                    .createTime(LocalDateTime.now())
                    .build().toString()
            );
        }
    }


}
